// @flow
import React from 'react'
import styles from './ServicePage.css'
import { Button, Progress, Icon, Modal } from 'antd'
import NoticeMessage from '../NoticeMessage'
import Table from '../Table'
import R from 'ramda'
type Props = {
  nextStep: Function,
  preStep: Function,
  step: number,
  kmxName: string
}
type State = {
  rowData: Array<Object>,
  visible: boolean,
  selectRows: Array<Object>,
  currentMess: Object,
  disabled: boolean,
  progress: number,
  key: string,
  content: string,
  select: string
}
export default class ServicePage extends React.Component {
  props: Props
  state: State
  detailCheck: Function
  stepClick: Function
  getKmxInitService: Function
  detailCheck: Function
  handleOk: Function
  handleCancel: Function
  selectChange: Function
  start: Function
  getEveryOneMess: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      rowData: [],
      visible: false,
      disabled: true,
      selectRows: [],
      currentMess: {},
      progress: 0,
      key: '',
      content: '',
      select: ''
    }
    this.detailCheck = this.detailCheck.bind(this)
    this.stepClick = this.stepClick.bind(this)
    this.detailCheck = this.detailCheck.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.start = this.start.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.selectChange = this.selectChange.bind(this)
    this.getKmxInitService = this.getKmxInitService.bind(this)
    this.getEveryOneMess = this.getEveryOneMess.bind(this)
  }

  componentDidMount () {
    // this.getKmxInitService('KMX1')
  }

  componentWillReceiveProps (nextProps: Object) {
    if (!R.equals(nextProps.step, this.props.step) && nextProps.step === 5) {
      this.getKmxInitService(nextProps.kmxName)
    }
  }

  detailCheck (params: Object) {
    this.setState({ visible: true, key: params.data.id, content: params.data.message })
  }

  refreshItem (params: Object) {
    console.info(params)
    const submitData = [{ name: params.data.id, initServices: params.data.initServices }]
    this.getEveryOneMess(submitData)
  }

  handleOk () {
    this.setState({ visible: false })
  }

  handleCancel () {
    this.setState({ visible: false })
  }

  stepClick (val: string) {
    if (val === 'pre') {
      this.props.preStep(4)
    }
    if (val === 'next') {
      this.props.nextStep(0)
    }
  }

  // 查詢KMX初始化服務
  getKmxInitService (name: string) {
    const url = `${__CM_URL__}kmxes/${name}/installService`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'ServicePage.js')
      }
      this.setState({
        rowData: json.body.items.map((x) => {
          x.status = 'waiting'
          x.id = x.name
          x.message = ''
          return x
        }),
        select: 'all'
      })
    })
    .catch((err) => {
      console.error(err)
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

// 选择节点后触发
  start () {
    console.info('start.....')
    const { selectRows } = this.state
    this.getEveryOneMess(selectRows)
  }

  // 表格选择发生变化时触发
  selectChange (val: Array<Object>) {
    // console.info(val)
    this.setState((preState) => {
      return { selectRows: val, disabled: !R.equals(preState.selectRows, val) }
    })
  }

  // 递归遍历每一个
  getEveryOneMess (data: Array<Object>) {
    if (data.length === 0) return
    console.info(JSON.stringify(R.omit(['id', 'status', 'message'], data[0]), null, 4))
    this.setState({
      currentMess: {
        id: data[0].name,
        name: data[0].name,
        status: 'running',
        message: ''
      }
    })
    const url = `${__CM_URL__}kmxes/${this.props.kmxName}/installService`
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(R.omit(['id', 'status', 'message'], data[0]))
    })
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'ServicePage.js')
      }
      console.info(json)
      this.setState({
        currentMess: {
          id: data[0].name,
          name: data[0].name,
          status: 'success',
          message: ''
        },
        disabled: data.slice(1).length !== 0,
        progress: this.state.selectRows.length - data.slice(1).length
      })
      this.getEveryOneMess(data.slice(1))
    })
    .catch((err) => {
      console.error(err)
      this.setState({
        currentMess: {
          id: data[0].name,
          name: data[0].name,
          status: 'error',
          message: (err && err.message) ? err.message : err
        }
      })
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  render () {
    const columnDefs = [
      {
        headerName: '',
        checkboxSelection: true,
        suppressMenu: true,
        suppressSorting: true,
        width: 70,
        headerCheckboxSelection: true,
        cellStyle: { padding: '8px', textAlign: 'center' }
        // cellRenderer: (params) => {
        //   // console.info(params)
        //   params.node.setSelected(true)
        // }
      },
      {
        headerName: '信息',
        field: 'message',
        hide: true
      },
      {
        headerName: '主机',
        field: 'name',
        suppressMenu: true,
        cellStyle: { padding: '8px', textAlign: 'center' }
      },
      {
        headerName: '状态',
        field: 'status',
        suppressMenu: true,
        width: 300,
        cellStyle: { padding: '8px' },
        cellRenderer: (params) => {
          return `<span class='progress ${params.value === 'running' ? 'active' : ''} ${params.value}'></span>`
        }
      },
      {
        headerName: '报告',
        field: 'text',
        suppressMenu: true,
        cellStyle: { padding: '8px', textAlign: 'center' },
        cellRendererFramework: (params: Object) => {
          if (params.data.status === 'success') {
            return <div className={styles['link']}>成功</div>
          } else if (params.data.status === 'error') {
            return <div className={styles['link']}>
              <a onClick={() => { this.detailCheck(params) }}>详细报告</a>
              <p><Icon type='sync' onClick={() => { this.refreshItem(params) }} /></p>
            </div>
          } else {
            return <span>等待运行...</span>
          }
        }
      }
    ]
    const { rowData, visible, currentMess, disabled, progress, selectRows, content, key, select } = this.state
    return (
      <div className={styles['content']}>
        <div className={styles['main']}>
          <div className={styles['progress']}>
            <Progress
              percent={selectRows.length === 0 ? 0 : progress * (100 / selectRows.length)}
              showInfo={false} strokeWidth={25} status='active' />
          </div>
          <div className={styles['table']}>
            <Table
              columnDefs={columnDefs}
              rowData={rowData}
              selectChange={this.selectChange}
              select={select}
              currentMess={currentMess}
              step={this.props.step}
            />
          </div>
        </div>
        <div className={styles['btn']}>
          <div style={{ float: 'right' }}>
            {
              // <Button onClick={() => { this.stepClick('pre') }}>上一步</Button> &emsp;
            }
            <Button onClick={this.start}>开始</Button>&emsp;
            <Button onClick={() => { this.stepClick('next') }} type='primary' disabled={disabled}>下一步</Button>
          </div>
        </div>
        <Modal
          visible={visible}
          title={key || ''}
          key={key || ''}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[
            <Button size='small' onClick={this.handleOk}>
              关闭
            </Button>
          ]}
        >
          <p>{content || ''}</p>
        </Modal>
      </div>
    )
  }
}
